package com.zhenhao.xsq.netsdk_demo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.sdk.NETDEV_PTZ_ZOOM_AREA_INFO_S;
import com.sdk.NetDEVSDK;
import com.zhenhao.xsq.ui.activity.video.VideoSwitchListene;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;

import static com.zhenhao.xsq.netsdk_demo.CMainMenu.lpLiveViewHandle;

public class CPlayView extends GLSurfaceView {
    private final String TAG = "CPlayView";

    public boolean m_bCanDrawFrame = true; // false 当前窗口是否播放
    private boolean m_bRenderInited = false; // render
    public int m_dwWinIndex = 1; // 窗口分屏索引

    //    声明Paint对象
    private Paint mPaint = null;
    private int StrokeWidth = 5;
    private Rect rect = new Rect(0, 0, 0, 0);//手动绘制矩形

    /**
     * 记录是拖拉照片模式还是放大缩小照片模式
     */
    private int mode = 0;// 初始状态
    /**
     * 拖拉照片模式
     */
    private static final int MODE_DRAG = 1;
    /**
     * 放大缩小照片模式
     */
    private static final int MODE_ZOOM = 2;

    /**
     * 当前放大的倍数
     */
    private float mCurrentRate = 1;
    /**
     * 上一次放大的倍数
     */
    private float mOldRate = 1;
    /**
     * 刚触摸时两个手指的距离
     */
    private float mOriginalLength;
    /**
     * 当前两个手指的距离
     */
    private float mCurrentLength;
    private float scaleEx = 1.0f;

    float xLastMove = 0.0f;
    float yLastMove = 0.0f;
    float fTotal = 0.0f;
    private float[] fCenterPosition;

    private Activity mActivity;
    private VideoSwitchListene videoSwitchListene;

    public void setmActivity(Activity mActivity) {
        this.mActivity = mActivity;
    }

    public void setVideoSwitchListene(VideoSwitchListene videoSwitchListene) {
        this.videoSwitchListene = videoSwitchListene;
    }

    public CPlayView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        //setEGLContextClientVersion(2);
        Log.d("------------", "PlayView(Context context)");
        //   init(false, 0, 0);

    }

    public CPlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //构建对象
        mPaint = new Paint();
        mPaint.setColor(Color.RED);

        // Log.i(“----------------------------------”, “PlayView(Context context, AttributeSet
        // attrs)”);
        Log.d(TAG+"------------ CPlayView ", "PlayView(Context context, AttributeSet attrs)");
        // TODO Auto-generated constructor stub
        //mContext = context;  
        //setEGLContextClientVersion(2);
        init(false, 0, 0);
        setWillNotDraw(false);
        /*setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_POINTER_DOWN:
                        Log.e(TAG, "MotionEvent.ACTION_POINTER_DOWN");
                        mode = MODE_ZOOM;
                        mOriginalLength =
                                (float) Math.sqrt(Math.pow(event.getX(0) - event.getX(1), 2) + Math.pow(event.getY(0) - event.getY(1), 2));

                        //0.47-0.53有效
                        float percentX =
                                0.47f + ((event.getX(0) + event.getX(1)) / 2) / (getWidth()) * 0.06f;
                        float percentY =
                                0.53f - ((event.getY(0) + event.getY(1)) / 2) / (getHeight()) * 0.06f;

                        //数字放大手指中心点
                        fCenterPosition = new float[]{percentX, percentY};
                        break;
                    // 手指压下屏幕
                    case MotionEvent.ACTION_DOWN:
                        Log.e(TAG, "MotionEvent.ACTION_DOWN");
                        mode = MODE_DRAG;
                        xLastMove = event.getX();
                        yLastMove = event.getY();
                        rect.left = (int) event.getX();
                        rect.top = (int) event.getY();
//                int id = mPlayerView.getId();
                        break;
                    // 当触点离开屏幕，但是屏幕上还有触点(手指)
                    case MotionEvent.ACTION_POINTER_UP:
                        Log.e(TAG, "MotionEvent.ACTION_POINTER_UP");
                        mode = 0;
                        break;

                    case MotionEvent.ACTION_MOVE:
                        Log.e(TAG, "MotionEvent.ACTION_MOVE");
                        rect.right = (int) event.getX();
                        rect.bottom = (int) event.getY();
                        invalidate();
                        if (mode == MODE_DRAG) {// 平移
                            float fSum = (float) (scaleEx * 0.5 - 0.5);
                            float X = 0.5f;
                            float Y = 0.5f;

                            X = X - (event.getX() - xLastMove) / (getWidth());
                            Y = Y + (event.getY() - yLastMove) / (getHeight());


                            float[] fPosition = new float[]{X, Y};
                            NetDEVSDK.Scale(scaleEx, fPosition[0], fPosition[1], m_dwWinIndex);

                            xLastMove = event.getX();
                            yLastMove = event.getY();

                        } else if (mode == MODE_ZOOM) {// 缩放
                            mCurrentLength =
                                    (float) Math.sqrt(Math.pow(event.getX(0) - event.getX(1), 2) + Math.pow(event.getY(0) - event.getY(1), 2));
                            if (Math.abs(mCurrentLength - mOriginalLength) > 10) {

                                mCurrentRate =
                                        (float) (mOldRate * (mCurrentLength / mOriginalLength));

                                //通过两个手指间距离判断放大还是缩小
                                boolean isLager = (mCurrentLength > mOriginalLength);

                                if (isLager) {
                                    scaleEx += 0.1f;
                                    //0.05为误差
                                    if (scaleEx >= 10.05f) {
                                        scaleEx = 10.0f;
                                    } else {
                                        //根据中心点放大
                                        NetDEVSDK.Scale(scaleEx, fCenterPosition[0],
                                                fCenterPosition[1], m_dwWinIndex);
                                    }
                                } else {
                                    float[] fPosition = new float[]{0.5f, 0.5f};
                                    scaleEx -= 0.1f;
                                    //0.05为误差
                                    if (scaleEx <= 0.95f) {
                                        scaleEx = 1.0f;
                                    } else {
                                        //通过画面中心缩小，防止画面位置飘走
                                        NetDEVSDK.Scale(scaleEx, fPosition[0], fPosition[1],
                                                m_dwWinIndex);

                                    }
                                }
                                mOriginalLength = mCurrentLength;

                                mOldRate = mCurrentRate;

                                fTotal = 0.0f;
                            }
                        }
						*//*NetDEVSDK.gdwWinIndex = 1;
						float percentX1 = 0.5f + event.getX()/m_oPlayer.getWidth();
						float percentY1 = 0.5f - event.getY()/m_oPlayer.getHeight();
						NetDEVSDK.Scale(scaleRatio[0], percentX1, percentY1, NetDEVSDK
						.gdwWinIndex);
						*//*
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.e(TAG, "MotionEvent.ACTION_UP");
						*//*
						NetDEVSDK.gdwWinIndex = 1;
						float percentX = 0.5f + event.getX()/m_oPlayer.getWidth();
						float percentY = 0.5f -  event.getY()/m_oPlayer.getHeight();
						scaleRatio[0] += 0.5f;
						if (scaleRatio[0] > 10.05f)
						{
							scaleRatio[0] = 1.0f;
						}
						NetDEVSDK.Scale(scaleRatio[0], percentX, percentY, NetDEVSDK.gdwWinIndex);
						*//*

                        NetDEVSDK.gdwWinIndex = m_dwWinIndex;
                        if (true == CMainMenu.b3DFlag) {
                            NETDEV_PTZ_ZOOM_AREA_INFO_S stZoomAreaInfo =
                                    new NETDEV_PTZ_ZOOM_AREA_INFO_S();
                            Rect dstRect = new Rect();
                            if (ConvertRectToNetSDK(dstRect)) {
                                stZoomAreaInfo.udwMidPointX = (dstRect.left + dstRect.right) / 2;
                                stZoomAreaInfo.udwMidPointY = (dstRect.top + dstRect.bottom) / 2;
                                stZoomAreaInfo.udwLengthX = (dstRect.right - dstRect.left);
                                stZoomAreaInfo.udwLengthY = (dstRect.bottom - dstRect.top);
                                //stZoomAreaInfo.udwWidth = getWidth();
                                //stZoomAreaInfo.udwHeight = getHeight();
                                int iRet =
                                        NetDEVSDK.NETDEV_PTZ3DPosition(lpLiveViewHandle[NetDEVSDK.gdwWinIndex - 1], stZoomAreaInfo);
                                if (0 == iRet)
                                    Toast.makeText(getContext(), "3DPosition failed!",
                                            Toast.LENGTH_SHORT).show();
                                else
                                    Toast.makeText(getContext(), "3DPosition succeed!",
                                            Toast.LENGTH_SHORT).show();
                            }
                        }
                        rect.left = 0;
                        rect.top = 0;
                        rect.right = 0;
                        rect.bottom = 0;
                        invalidate();
                        //invalidate(rect);
                        break;
                }

                return true;
            }
        });*/
    }

    private boolean ConvertRectToNetSDK(Rect dstRect) {
        Rect oSrcRt = new Rect();
        oSrcRt.right = getWidth();
        oSrcRt.bottom = getHeight();
        dstRect.left = rect.left;
        dstRect.right = rect.right;
        dstRect.top = rect.top;
        dstRect.bottom = rect.bottom;

        dstRect.left = (dstRect.left * 10000) / oSrcRt.right;
        dstRect.right = (dstRect.right * 10000) / oSrcRt.right;
        dstRect.top = (dstRect.top * 10000) / oSrcRt.bottom;
        dstRect.bottom = (dstRect.bottom * 10000) / oSrcRt.bottom;

        dstRect.right = ((dstRect.right < dstRect.left) ? dstRect.left : dstRect.right);  //right
        // 取大值，left取小值
        dstRect.left = ((dstRect.right < dstRect.left) ? dstRect.right : dstRect.left);
        dstRect.bottom = ((dstRect.bottom < dstRect.top) ? dstRect.top : dstRect.bottom);
        //bottom取大值，top取小值
        dstRect.top = ((dstRect.bottom < dstRect.top) ? dstRect.bottom : dstRect.top);

        /*int nIntervalX = rect.left < rect.right?(rect.right - rect.left):(rect.left - rect.right);
        int nIntervalY = rect.top < rect.bottom?(rect.bottom - rect.top):(rect.top - rect.bottom);
        if ( nIntervalX < 20 || nIntervalY <20)
        {
            return false;
        }*/
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //设置无锯齿
        mPaint.setAntiAlias(true);
        //canvas.drawARGB(50,255,227,0);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(StrokeWidth);
        mPaint.setAlpha(100);
        mPaint.setColor(Color.RED);
        canvas.drawRect(rect, mPaint);
    }

    private void init(boolean translucent, int depth, int stencil) {

        Log.d(TAG+"------------ CPlayView ", "init");
        /*
         * By default, GLSurfaceView() creates a RGB_565 opaque surface. If we
         * want a translucent one, we should change the surface's format here,
         * using PixelFormat.TRANSLUCENT for GL Surfaces is interpreted as any
         * 32-bit surface with alpha by SurfaceFlinger.
         */
        if (translucent) {
            this.getHolder().setFormat(PixelFormat.TRANSLUCENT);//使窗口支持透明度
        }

        //KLog.i(debug, KLog.wrapKeyValue("translucent", translucent));
        /*
         * Setup the context factory for 2.0 rendering. See ContextFactory class
         * definition below
         */
        setEGLContextFactory(new ContextFactory());//设置OpenGL ES的版本构建器(可自定义)
        /*
         * We need to choose an EGLConfig that matches the format of our surface
         * exactly. This is going to be done in our custom config chooser. See
         * ConfigChooser class definition below.
         */
        setEGLConfigChooser(translucent ? new ConfigChooser(8, 8, 8, 8, depth,
                stencil) : new ConfigChooser(5, 6, 5, 0, depth, stencil));//颜色、深度、模板等等设置
        /* Set the renderer responsible for frame rendering */
        ;
        //指定自定义渲染器
        setRenderer(new MyRenderer());
    }

    private class MyRenderer implements GLSurfaceView.Renderer {

        public MyRenderer() {
            super();
            //初始化显示业务
            int ret = NetDEVSDK.initialize();
            if (ret == 1) {
                m_bRenderInited = true;

            }
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            if (m_bCanDrawFrame && m_bRenderInited) {
                //视频数据解析
                NetDEVSDK.rendererRender(m_dwWinIndex);
//				KLog.i(debug, "onDrawFrame");
            } else {
                //清屏
                gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
            }
        }


        //GlSurfaceView尺寸发送变化时回调，例如横竖屏切换
        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            Log.e(TAG, "onSurfaceChanged "+width+" "+height);
            // TODO Auto-generated method stub
            //设置视频输出大小
            NetDEVSDK.setRendererViewport(width, height);
            if (videoSwitchListene != null) {
                videoSwitchListene.onVideoSwitch(1);
            }

        }

        //GlSurfaceView 创建的时候回调，可以做一些参数初始化操作
        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            Log.e(TAG, "onSurfaceCreated ");
            // TODO Auto-generated method stub
            //初始化显示解析
            NetDEVSDK.initializeRenderer(m_dwWinIndex);
        }
    }

}

